package com.dkm.modules.sys.user.service.impl;

import com.dkm.exception.ServiceException;
import com.dkm.modules.sys.user.mapper.CustomerBalanceMapper;
import com.dkm.modules.sys.user.model.CustomerBalance;
import com.dkm.modules.sys.user.model.User;
import com.dkm.modules.sys.user.service.CustomerBalanceService;
import com.dkm.modules.wx.card.mapper.RechargeRecodMapper;
import com.dkm.modules.wx.card.model.RechargeRecodPO;
import com.dkm.util.StringUtils;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * DESCRIPTION :
 *
 * @author ducf
 * @create 2019-12-20 22:14
 */
@Slf4j
@Service
public class CustomerBalanceServiceImpl implements CustomerBalanceService {

    @Autowired
    CustomerBalanceMapper customerBalanceMapper;

    @Autowired
    RechargeRecodMapper rechargeRecodMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void updateUserBalanceAndRecord(String openId, BigDecimal amount, String batchNo,
                                           Integer changeType, User user) {
        if (StringUtils.isBlank(openId)
                || Objects.isNull(amount)
                || BigDecimal.ZERO.compareTo(amount) == 0
                || Objects.isNull(user)) {
            throw new ServiceException("更新账户余额,金额或openid或操作人不能为空");
        }

        CustomerBalance customerBalance = this.selectByOpenId(openId);

        if (Objects.isNull(customerBalance)) {
            throw new ServiceException("注册用户账户不存在");
        }

        // 更新余额
        customerBalanceMapper.updateAmountByOpenId(openId, amount);

        // 充值记录
        RechargeRecodPO recodPO = RechargeRecodPO.builder()
                .openId(openId)
                .type(changeType)
                .dataType(2)
                .quantity(amount)
                .rechargeNumber(batchNo)
                .status(1)
                .openId(openId)
                .createBy(user.getId())
                .createTime(new Date())
                .build();
        // 记录变更记录
        rechargeRecodMapper.insert(recodPO);

        log.info("更新注册用户:{}的余额:{}", openId, amount);

    }

    @Override
    public CustomerBalance selectByOpenId(String openId) {
        if (StringUtils.isBlank(openId)) {
            throw new ServiceException("openId不能为空");
        }

        Map<String, Object> param = Maps.newHashMap();
        param.put("open_id", openId);

        List<CustomerBalance> userBalances = customerBalanceMapper.selectByMap(param);

        if (CollectionUtils.isEmpty(userBalances)) {
            return null;
        }

        return userBalances.get(0);
    }


}
